import dayjs from 'dayjs'

import { html, useSvg } from '../shui'
import { ShElement } from './ShElement'

import iconUrl from './icons.svg'



export class ShCalendar extends ShElement { 

    private _value: string = ''
    private _ym!: dayjs.Dayjs

    constructor() {
        super()

        this.$shadow.append(...html`
            <style>
                :host {
                    display: flex;
                    flex-direction: column;
                }
                #head {
                    line-height: 2.5em;
                    border-bottom: var(--border-ctrl);
                    display: flex;
                    align-items: center;
                }
                .nav {
                    width: 2.5em;
                    height: 2.5em;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                }
                .nav:hover {
                    background-color: var(--color-primary-lite);
                }
                .nav:active {
                    background-color: var(--color-primary-lite2);
                }
                .nav:hover > svg > use { stroke: var(--color-primary); }
                #yearMonth {
                    flex-grow: 1;
                    font-weight: bold;
                    text-align: center;
                }
                #neck {
                    line-height: 2.5em;
                    border-bottom: var(--border-ctrl);
                    display: flex;
                }
                #neck > div {
                    flex-grow: 1;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                #neck > div:nth-child(6) { color: green; }
                #neck > div:nth-child(7) { color: red; }
                #body {
                    display: grid;
                    grid-template-columns: repeat(7, 1fr);
                }
                #body > span {
                    height: 30px;
                    background-color: white;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                #body > span:not(.sh-disabled):hover {
                    background-color: var(--color-primary-lite);
                    color: var(--color-primary);
                }
                #body > span:not(.sh-disabled):active {
                    background-color: var(--color-primary);
                    color: white;
                }
                #body > span.today {
                    color: var(--color-primary);
                    border: solid 1px var(--color-primary);
                }
                #foot {
                    padding: 0.5em;
                    border-top: var(--border-ctrl);
                    display: flex;
                    justify-content: center;
                }
            </style>
            <div id="head">
                <div class="nav" @click=${this.btnPrevYearClick}>${useSvg(iconUrl + '#double-left', '14px', 'black', 'none')}</div>
                <div class="nav" @click=${this.btnPrevMonthClick}>${useSvg(iconUrl + '#left', '14px', 'black', 'none')}</div>
                <div id="yearMonth"></div>
                <div class="nav" @click=${this.btnNextMonthClick}>${useSvg(iconUrl + '#right', '14px', 'black', 'none')}</div>
                <div class="nav" @click=${this.btnNextYearClick}>${useSvg(iconUrl + '#double-right', '14px', 'black', 'none')}</div>
            </div>
            <div id="neck">
                <div>一</div>
                <div>二</div>
                <div>三</div>
                <div>四</div>
                <div>五</div>
                <div>六</div>
                <div>日</div>
            </div>
            <div id="body">
            </div>
            <div id="foot">
                <sh-button primary small @click=${this.btnTodayClick}>今天</sh-button>
            </div>
        `)

        // 设置 this._ym 并据此绘制本月日历
        this.setYearMonth(dayjs())
    }

    public get value(): string {
        return this._value
    }

    public set value(v: string) {
        const d = dayjs(v)
        this._value = d.format('YYYY-MM-DD')

        ;(this.$shadow.querySelector('span.sh-selected') as HTMLElement | null)?.removeClass('sh-selected')
        this.setYearMonth(d)
        ;(this.$shadow.querySelector(`span[date="${this._value}"]`) as HTMLElement | null)?.addClass('sh-selected')

        this.dispatchEvent(new CustomEvent('shev-select', { detail: this._value }))
    }

    public setYearMonth(ym: dayjs.Dayjs) {
        this._ym = ym
        this.$shadow.getElementById('yearMonth')!.textContent = this._ym.year() + ' 年 ' + (this._ym.month() + 1) + ' 月'

        const $body = this.$shadow.getElementById('body')!
        $body.innerHTML = ''

        const firstDay = this._ym.startOf('month')
        const lastDay = this._ym.endOf('month')

        let d = firstDay.subtract((firstDay.day() + 6) % 7, 'day')
        while (true) {
            for (let i = 0; i < 7; i++) {
                const $span = document.createElement('span')
                $span.textContent = d.date().toString()
                $span.setAttribute('date', d.format('YYYY-MM-DD'))

                if (d.format('YYYY-MM-DD') === this._value)
                    $span.addClass('sh-selected')

                if (d.isSame(dayjs(), 'day'))
                    $span.addClass('today')

                if (d.month() !== this._ym.month())
                    $span.addClass('sh-disabled')

                $span.on('click', this.dateClick.bind(this, $span))

                $body.append($span)
                d = d.add(1, 'day')
            }
            if (d.isAfter(lastDay))
                break
        }
    }

    private btnPrevYearClick = () => {
        this.setYearMonth(this._ym.subtract(1, 'year'))
    }

    private btnPrevMonthClick = () => {
        this.setYearMonth(this._ym.subtract(1, 'month'))
    }

    private btnNextMonthClick = () => {
        this.setYearMonth(this._ym.add(1, 'month'))
    }

    private btnNextYearClick = () => {
        this.setYearMonth(this._ym.add(1, 'year'))
    }

    private btnTodayClick = () => {
        this.value = dayjs().format('YYYY-MM-DD')
    }

    private dateClick = ($span: HTMLSpanElement) => {
        if ($span.hasClass('sh-disabled'))
            return
        this.value = $span.getAttribute('date') || ''
    }
}
customElements.define('sh-calendar', ShCalendar)